<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-下脚料品种`"
		width="1000px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="种类" prop="typeId">
						<jk-select v-model="ruleForm.typeId" style="width: 100%;" :option-list="materialList" placeholder="种类" clearable size="medium" @change="OnchangeMaterial"></jk-select>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="品种名称" prop="name">
						<div class="flex-start-center">
							<el-input v-model="ruleForm.name" placeholder="品种名称" />
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<jk-table border :data="ruleForm.standardList || []" :max-height="dialogTableHeight - 30">
			<vxe-column title="操作" align="center" field="operation" :width="110">
				<template slot-scope="scope">
					<div class="flex-center">
						<jk-button size="mini" icon="el-icon-plus" class="item-gap" @click="onAddBtn(scope.rowIndex)"></jk-button>
						<jk-button :disabled="scope.rowIndex===0" size="mini" icon="el-icon-minus" @click="onRemoveBtn(scope.rowIndex)"></jk-button>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="序号" type="seq" align="center" :width="60"></vxe-column>
			<vxe-column title="最小标准百分比" align="left" field="minStandard" :min-width="120">
				<template slot-scope="scope">
					<jk-input v-model="scope.row.minStandard" placeholder="最小标准百分比(必填)" size="mini"></jk-input>
				</template>
			</vxe-column>
			<vxe-column title="最大标准百分比" align="left" field="maxStandard" :min-width="120">
				<template slot-scope="scope">
					<jk-input v-model="scope.row.maxStandard" placeholder="最大标准百分比(必填)" size="mini"></jk-input>
				</template>
			</vxe-column>
			<vxe-column title="选择月份" align="center" field="startYearMonth" :min-width="360">
				<template slot-scope="scope">
					<div class="flex-start-center">
						<el-date-picker
							v-model="scope.row.startYearMonth"
							size="mini"
							type="month"
							format="yyyy-MM"
							:picker-options="{
								disabledDate: (date) =>
									isDisabledMonth(date, scope.row),
							}"
							value-format="yyyy-MM"
							placeholder="选择开始月份(必填)"
						>
						</el-date-picker>
						<span style="margin: 0 6px">-</span>
						<el-date-picker
							v-model="scope.row.endYearMonth"
							size="mini"
							type="month"
							format="yyyy-MM"
							value-format="yyyy-MM"
							:picker-options="{
								disabledDate: (date) => isDisabledMonth(date, scope.row)
							}"
							placeholder="选择结束月份(必填)"
						>
						</el-date-picker>
					</div>
				</template>
			</vxe-column>
		</jk-table>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { formatMonth, formatDate, formatTime } from '../../../utils/jk/jk-tool';
    import remoteSearchProductInput from '../../technology/order/components/remote-search-product-input/index';
    import { spinMaterialCreate, spinMaterialGet, spinMaterialUpdate, systemBusinessDictPage } from '@/api/material/rawMaterial';
    export default {
        name: 'LeftoverMaterial',
        mixins: [calHeight],
        components: { remoteSearchProductInput },
        props: {
            formData: {
                type: Object,
                default() {
                    return {};
                }
            },
            // 是否默认品种
            isDefaultProduct: {
                type: Boolean,
                default: false
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                tableLoading: false,
                saveBtnLoading: false,
                materialList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    typeId: undefined,
                    name: undefined,
                    typeCode: undefined,
                    typeName: undefined,
                    auditState: 1,
                    standardList: [{
                        minStandard: undefined,
                        maxStandard: undefined,
                        startYearMonth: undefined,
                        endYearMonth: undefined
                    }]
                },
                defaultRowItem: {
                    minStandard: undefined,
                    maxStandard: undefined,
                    startYearMonth: undefined,
                    endYearMonth: undefined
                },
                rules: {
                    typeId: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            OnchangeMaterial(val) {
                this.materialList.forEach((x) => {
                    if (val === x.id) {
                        this.$set(this.ruleForm, 'typeName', x.name);
                        this.$set(this.ruleForm, 'typeId', x.id);
                        this.$set(this.ruleForm, 'typeCode', x.code);
                    }
                });
            },
            onSelectProductChange(e) {
                if (Object.keys(e).length) {
                    this.setDependentData(e);
                }
            },
            setDependentData(e) {
                this.$set(this.ruleForm, 'productId', e.id);
                this.$set(this.ruleForm, 'productCode', e.code);
                this.$set(this.ruleForm, 'productName', e.name);
                this.$set(this.ruleForm, 'productModels', e.models);
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                return params;
            },
            validateStandardList() {
                const list = this.ruleForm.standardList || [];
                for (let i = 0; i < list.length; i++) {
                    const item = list[i];
                    if (!item.minStandard && item.minStandard !== 0) {
                        this.$message.warning(`第 ${i + 1} 行最小标准百分比不能为空`);
                        return false;
                    }
                    if (!item.maxStandard && item.maxStandard !== 0) {
                        this.$message.warning(`第 ${i + 1} 行最大标准百分比不能为空`);
                        return false;
                    }
                    if (!item.startYearMonth) {
                        this.$message.warning(`第 ${i + 1} 行月份不能为空`);
                        return false;
                    }
                }
                return true;
            },
            // 获取两个年月之间的所有月份（包含起止）
            getRangeMonths(start, end) {
                const result = [];
                let [startY, startM] = start.split('-').map(Number);
                const [endY, endM] = end.split('-').map(Number);

                while (startY < endY || (startY === endY && startM <= endM)) {
                    result.push(`${startY}-${startM.toString().padStart(2, '0')}`);
                    startM++;
                    if (startM > 12) {
                        startM = 1;
                        startY++;
                    }
                }

                return result;
            },

            isDisabledMonth(date, currentRow) {
                const currentMonth = formatMonth(date);
                const disabledMonths = this.ruleForm.standardList.flatMap(row => {
                    if (row === currentRow || !row.startYearMonth || !row.endYearMonth) return [];
                    return this.getRangeMonths(row.startYearMonth, row.endYearMonth);
                });

                return disabledMonths.includes(currentMonth);
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        if (!this.validateStandardList()) return;
                        for (
                            let i = 0;
                            i < this.ruleForm.standardList.length;
                            i++
                        ) {
                            const item = this.ruleForm.standardList[i];

                            // 校验最大标准值 > 最小标准值
                            if (
                                Number(item.minStandard) >= Number(item.maxStandard)
                            ) {
                                this.$message.warning(
                                    `第 ${i + 1} 行最大标准百分比需大于最小值`
                                );
                                return;
                            }

                            // 校验结束月份 > 开始月份
                            if (item.startYearMonth > item.endYearMonth) {
                                this.$message.warning(
                                    `第 ${i + 1} 行结束月份应晚于开始月份`
                                );
                                return;
                            }
                        }

                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onAddBtn(index) {
                if (index || index === 0) {
                    this.ruleForm.standardList.splice(index + 1, 0, JSON.parse(JSON.stringify(this.defaultRowItem)));
                } else {
                    this.ruleForm.standardList.push(JSON.parse(JSON.stringify(this.defaultRowItem)));
                }
            },
            onRemoveBtn(index) {
                if (this.ruleForm.standardList.length > 1) {
                    this.ruleForm.standardList.splice(index, 1);
                }
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? spinMaterialCreate : spinMaterialUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                const params = {
                    categoryCode: 'MATERIAL_TYPE',
                    pageNo: '1',
                    pageSize: '100'
                };
                return systemBusinessDictPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.materialList = res.data.res;
                    }
                });
            },
            getSpinMaterialGet() {
                return spinMaterialGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                        if (!this.ruleForm.typeName) {
                            this.$set(this.ruleForm, 'typeName', res.data.res.typeName);
                        }
                        if (!this.ruleForm.typeCode) {
                            this.$set(this.ruleForm, 'typeCode', res.data.res.code);
                        }
                        if (!this.ruleForm.standardList) {
                            this.ruleForm.standardList = [(JSON.parse(JSON.stringify(this.defaultRowItem)))];
                        }
                    }
                });
            },

            async getDependentData() {
                this.showLoading = true;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'batchDate', formatDate(Date.now()));
                }
                if (this.isDefaultProduct) {
                    this.$set(this.ruleForm, 'productId', this.formData.productId);
                    this.$set(this.ruleForm, 'productCode', this.formData.productCode);
                    this.$set(this.ruleForm, 'productName', this.formData.productName);
                    this.$set(this.ruleForm, 'productModels', this.formData.productModels);
                }
                if (this.dataId) await this.getSpinMaterialGet();
                await this.getDetailRequest(); // 物料给默认值
                if (!this.ruleForm.typeId) {
                    this.materialList.forEach((x) => {
                        if (x.name === '下脚料') {
                            this.$set(this.ruleForm, 'typeName', x.name);
                            this.$set(this.ruleForm, 'typeId', x.id);
                            this.$set(this.ruleForm, 'typeCode', x.code);
                        }
                    });
                }
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
